

/* NicEdit - Micro Inline WYSIWYG
 * Copyright 2007-2008 Brian Kirchoff
 *
 * NicEdit is distributed under the terms of the MIT license
 * For more information visit http://nicedit.com/
 * Do not remove this copyright message
 */

var zmdoc = zmdoc||{};
 var nicLang = {
      'bold' : '加粗'
      ,'italic' : '斜体'
      ,'underline' : '下划线'
      ,'left' : '左对齐'
      ,'code' : '代码'
      ,'center' : '居中对齐'
      ,'right' : '右对齐'
      ,'justify' : '两端对齐'
      ,'ol' : '有序列表'
      ,'ul' :  '无序列表'
      ,'subscript' : '下标'
      ,'superscript' : '上标'
      ,'strikethrough' : '删除线'
      ,'removeformat' : '删除格式'
      ,'indent' : '缩进'
      ,'outdent' : '删除缩进'
      ,'hr' : '分隔线'
      ,'image':'添加图片'
      ,'save':'保存内容'
      ,'submit':'提交'
      ,'uploadImage':'上传图片'
      ,'uploadFile':'上传文件'
      ,'uploadFailed':'上传图片失败'
      ,'uploadImageTypeLimit':'只能上传png和jpg格式的图片'
      ,'uploadImageSizeLimit':'图片不能大于1M'
      ,'uploadFileFailed':'上传文件失败'
      ,'uploadFileTypeLimit':'只能上传XXX格式的文件'
      ,'uploading' : '上传中...'
      ,'img':{
         'title':'添加/编辑图片'
         ,'url':'址址'
         ,'alt':'替换文本'
         ,'align':'对齐'
         ,'default':'默认'
         ,'left':'左对齐'
         ,'right':'右对齐'
         ,'wrongUrl':'图片地址格式不正确'
      }
      ,'forecolor':'文本颜色'
      ,'bgcolor':'背景颜色'
      ,'fontSize':'字号'
      ,'fontFamily':'字体'
      ,'fontFormat':'格式'
      ,'sel':{
         'fontFamily' : {
               'SimSun'             : '宋体',
               'SimHei'             : '黑体',
               'FangSong_GB2312'    : '仿宋体',
               'KaiTi_GB2312'       : '楷体',
               'NSimSun'            : '新宋体',
               'Arial'              : 'Arial',
               'Arial Black'        : 'Arial Black',
               'Times New Roman'    : 'Times New Roman',
               'Courier New'        : 'Courier New',
               'Tahoma'             : 'Tahoma',
               'Verdana'            : 'Verdana'
           }
      }
      ,'link':'添加/编辑链接'
      ,'unlink':'删除链接'
      ,'links' : {
         'tit':'添加/编辑链接'
         ,'url':'链接'
         ,'title':'提示'
         ,'target':'窗口'
         ,'error':'链接格式不正确'
         ,'currentWindow':'当前窗口'
         ,'newWindow':'新窗口'
      }
      ,'pre':'代码'
      ,'p':'段落'
      ,'h1':'一级标题'
      ,'h2':'二级标题'
      ,'h3':'三级标题'
      ,'h4':'四级标题'
 };

zmdoc._editor_cls_prefix = 'zmdoc';

if(typeof Ext != 'undefined'&&typeof Ext.langs != 'undefined'){
	nicLang = Ext.langs.nicLang;
};

var nicEditorConfig = $ZClass.extend({
	buttons : {
		'bold' : {name : nicLang.bold, command : 'Bold', tags : ['B','STRONG'], css : {'font-weight' : 'bold'}, key : 'b'},
		'italic' : {name : nicLang.italic, command : 'Italic', tags : ['EM','I'], css : {'font-style' : 'italic'}, key : 'i'},
		'underline' : {name : nicLang.underline, command : 'Underline', tags : ['U'], css : {'text-decoration' : 'underline'}, key : 'u'},
		
		'pre' : {name : nicLang.pre, command : 'formatBlockPRE',tags : ['PRE'], noActive : true},
		'p' : {name : nicLang.p, command : 'formatBlockP',tags : ['P'], noActive : true},

		'h1' : {name : nicLang.h1, command : 'formatBlockH1',tags : ['H1'], noActive : true},
		'h2' : {name : nicLang.h2, command : 'formatBlockH2',tags : ['H2'], noActive : true},

		'left' : {name : nicLang.left, command : 'justifyleft', noActive : true},
		'center' : {name : nicLang.center, command : 'justifycenter', noActive : true},
		'right' : {name : nicLang.right, command : 'justifyright', noActive : true},
		'justify' : {name : nicLang.justify, command : 'justifyfull', noActive : true},
		'ol' : {name : nicLang.ol, command : 'insertorderedlist', tags : ['OL']},
		'ul' : 	{name : nicLang.ul, command : 'insertunorderedlist', tags : ['UL']},
		'subscript' : {name : nicLang.subscript, command : 'subscript', tags : ['SUB']},
		'superscript' : {name : nicLang.superscript, command : 'superscript', tags : ['SUP']},
		'strikethrough' : {name : nicLang.strikethrough, command : 'strikeThrough', css : {'text-decoration' : 'line-through'}},
		'removeformat' : {name : nicLang.removeformat, command : 'removeformat', noActive : true},
		'indent' : {name : nicLang.indent, command : 'indent', noActive : true},
		'outdent' : {name : nicLang.outdent, command : 'outdent', noActive : true},
		'hr' : {name : nicLang.hr, command : 'insertHorizontalRule', noActive : true}
	},
	iconsPath : 'http://www.dasdoc.com/ys-pub/resources/images/zm/zmdoc-tools-b.png',
	loadingPath : 'http://www.dasdoc.com/ys-pub/resources/images/default/grid/loading.gif',
	buttonList : ['bold','italic','underline','left','center','ol','ul','h1','h2','p','indent','outdent','image','upload','link','unlink','forecolor','bgcolor','xhtml'],
	iconList : {"xhtml":1,
		"bgcolor":15,
		"forecolor":14,
		"bold":3,
		"center":17,
		"indent":8,
		"italic":4,
		"left":16,
		"ol":6,
		"outdent":7,
		"code":24,
		"ul":5,
		"underline":22,
		"image":9,
		"link":13,
		"unlink":12,
		"p":23,
		"arrow":26,
		"h1":27,
		"h2":28,
		"upload":11}
	
});

/* END CONFIG */



//开发者第三方插件
var nicPlugins = [];

var nicEditor = $ZClass.extend({
	construct : function(el,o) {
		this.options = new nicEditorConfig();
		$ZExtend(this.options,o);
		
		
		var plugins = nicPlugins;
		
		if(typeof(el) == 'string') {
			var e = $Z('#'+el);
		} else {
			var e = $Z(el);
		}

		for(var i=0;i<plugins.length;i++) {
			new plugins[i].p(this,plugins[i].o);
		}
		//nicEditors.editors.push(this);
		
		$Z.on(document.body,'mousedown', this.selectCheck.closureListener(this) );

		//编辑器
		//add width 
		//edit by klj 2013-11-01
		var wrapper = new $ZElement('DIV').css({border:'1px solid #DDD',
		  '-webkit-box-sizing': 'border-box',
		     '-moz-box-sizing': 'border-box',
		          'box-sizing': 'border-box',
			'position':'relative',width:(this.options.width?this.options.width+'px':'100%')}).before(e);
		wrapper.id = e.id + '____wrapper';


		
		//初始化菜单
		this.setPanel(wrapper);
		//初始化编辑区
		
		if( e.contentEditable || !!window.opera ) {
			this.selectedInstance = new nicEditorInstance(e,this,wrapper);
		} else {
			this.selectedInstance = new nicEditorIFrameInstance(e,this,wrapper);
		}

		wrapper.on('paste',(function(e) {
			var ne = this.selectedInstance;
			var content = ne.getContent();
			if(content.length < 10) {
				setTimeout(function(){
					var content = ne.getContent();
					
					//content = content.replace(/<\s*([^img|a]\w+).*?>/img, '<$1>').replace(/<\s*p.*?>/img, '<p>');
					content = content.replace(/<script.*>.*<\/script>/img, '');
					content = content.replace(/<style>[^<]*<\/style>/img, '');

					content = content.replace(/\s*<([^ai]\w+)[^>]*>/img,'<$1>');
					content = content.replace(/\s*<(p)[^>]*>/img,'<$1>');

					content = content.replace(/<span>([^<]*)<\/span>/img, '$1');


					
					//remove blank line
					content = content.replace(/^\s*[\r\n]/gm,'');

			
					ne.html(content);
				},50)

			}
		}).closureListener(this));

		return this;

	},
	


	setPanel : function(e) {
		this.nicPanel = new nicEditorTools($Z(e),this.options,this);
		this.fireEvent('panel',this.nicPanel);
		//nicplugin line812; this.ne.on('panel',this.loadPanel.closure(this));
		return this;
	},
	
	nicCommand : function(cmd,args) {
		if(this.selectedInstance) {
			var i =  cmd.indexOf('formatBlock');
			if(cmd.indexOf('formatBlock')>-1){
				args = cmd.slice(11);
				cmd = 'formatBlock';

			}
			this.selectedInstance.nicCommand(cmd,args);
		}
	},
	
	getIcon : function(iconName,options) {
		var icon = this.options.iconList[iconName];
		var file = (options.iconFiles) ? options.iconFiles[iconName] : '';
		return {backgroundImage : "url('"+((icon) ? this.options.iconsPath : file)+"')",'backgroundSize': 'auto 25px', backgroundPosition : ((icon) ? ((icon-1)*-25) : 0)+'px 50%'};	
	},

	selectCheck : function(e,t) {
		var found = false;
		do{
			if(t.id && t.id == this.nicPanel.elm.id) {
				return false;
			}
		} while(t = t.parentNode);
		this.fireEvent('blur',this.selectedInstance,t);
		// this.lastSelectedInstance = this.selectedInstance;
		// this.selectedInstance = null;
		return false;
	},

	on : function(evType, evFunc) {
		if(evFunc) {
			this.eventList = this.eventList || {};
			this.eventList[evType] = this.eventList[evType] || []; //if not, init it
			this.eventList[evType].push(evFunc);
		}
		return this;
	},
	fireEvent : function() {
		var args = $Z.toArray(arguments), evType = args.shift();
		
		if(this.eventList && this.eventList[evType]) {
			for(var i=0;i<this.eventList[evType].length;i++) {
				this.eventList[evType][i].apply(this,args);
			}
		}
	},
	mask : function(txt){
		var elm = this.nicPanel.elm,pos = elm.pos();
		var mask = $Z('#'+elm.id+'_mask');
		if(!mask){
			mask = new $ZElement('DIV').css({'display':'none','position':'absolute', 'opacity':'0.6', 'background':'#000','zIndex':'9999'}).before(elm);
			mask.id = elm.id + '_mask';
			var text = new $ZElement('DIV').css({'cursor':'wait','position':'absolute', 'top':'50%', 'left':'50%',marginLeft:'-50px',background:'url("'+(this.nicPanel.options.loadingPath)+'") no-repeat 5px 50% #fff', padding:'5px 5px 5px 25px'}).wrapper(mask);
			text.id = elm.id + '_maskText';
			
		};
		mask.css({'display':'block', 'z-index':100000, 'width':elm.css('width')
			,'height':elm.css('height'),'left':pos[0], 'top':pos[1]
		});
		$Z('#'+elm.id+'_maskText').html(txt);
		this.fireEvent('blur',this.nicPanel);
	},
	updateMaskText:function(txt){
		$Z('#'+this.nicPanel.elm.id+'_maskText').html(txt);
	},
	unmask : function(){
		$Z('#'+this.nicPanel.elm.id+'_mask').css({'display':'none'});
		this.fireEvent('focus',this.nicPanel);
	}
	
});
//nicEditor = nicEditor.extend(bkEvent);

//=================

var nicEditorInstance = $ZClass.extend({
	isSelected : false,
	
	construct : function(e,nicEditor,wrapper) {
		this.ne = nicEditor;
		this.elm = this.e = e;

		newY = parseInt(e.css('height')) || e.clientHeight;
		this.initialHeight = newY-8;
		
			var ie7s = ($Z.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat"));
			var s = {backgroundColor:'#FFF', borderTop : 0, overflowY : 'auto', overflowX: 'hidden' };
			s[(ie7s) ? 'height' : 'maxHeight'] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight+'px' : null;
			this.editorContain = new $ZElement('DIV').css(s).wrapper(wrapper);

			var editorElm = new $ZElement('DIV').css({margin: '4px'}).addClass(zmdoc._editor_cls_prefix+'').wrapper(this.editorContain);

			e.css({display : 'none'});
				
			
			//初始化时，把textarea里的初始内容展现出来
			editorElm.html(e.value);
			
			var f = e.parentTag('FORM');
			//if(f) { $Z.on( f, 'submit', this.saveContent.closure(this)); }
			(function(me) {
				setInterval(function() {
					me.saveContent();
				},200);
			})(this);
			
			//editorElm.css((ie7s) ? {height : newY+'px'} : (this.ne.options.fixedHeight ? {overflow: 'auto',height:newY+'px'} :{overflow: 'hidden'}));
			editorElm.css({overflow: 'auto',height:newY+'px'});
			this.elm = editorElm;	
		
		this.ne.on('blur',this.blur.closure(this));

		this.init();
		this.blur();
	},
	appendStyle:function(styles) {
		var ss = document.styleSheets;
		for (var i = 0, max = ss.length; i < max; i++) {
			if (ss[i].href == styles)
				return;
		}
		var css = document.createElement("link");
		css.setAttribute("rel", "stylesheet");
		css.setAttribute("type", "text/css");
		css.setAttribute("href", styles);
		document.getElementsByTagName("head")[0].appendChild(css);
	},
	init : function() {
		this.elm.setAttribute('contentEditable','true');	
		if(this.getContent() == "") {
			this.html('<br />');
		}
		this.instanceDoc = document.defaultView;//用于styles
		this.appendStyle(this.ne.options.ZMDOCSTYLE);
		this.elm.on('mousedown',this.selected.closureListener(this)).on('keypress',this.keyDown.closureListener(this)).on('focus',this.selected.closure(this)).on('blur',this.blur.closure(this)).on('keyup',this.selected.closure(this));
		this.ne.fireEvent('add',this);
	},
	
	remove : function() {
		this.saveContent();
		this.editorContain.remove();
		this.e.css({'display' : 'block'});
		this.ne.removePanel();
		
		this.disable();
		this.ne.fireEvent('remove',this);
	},
	
	disable : function() {
		this.elm.setAttribute('contentEditable','false');
	},
	
	getSel : function() {
		return (window.getSelection) ? window.getSelection() : document.selection;	
	},
	
	getRng : function() {
		var s = this.getSel();
		if(!s || s.rangeCount === 0) { return; }
		return (s.rangeCount > 0) ? s.getRangeAt(0) : s.createRange();
	},
	setRng: function(replacementText) {
		var sel = this.getSel(), range = this.getRng();
	   if (window.getSelection) {
	        if (sel.rangeCount) {
	            range.deleteContents();
	            range.insertNode(document.createTextNode(replacementText));//document.createTextNode(txt)
	            //range.selectNode(document.createTextNode(replacementText));
	        }
	    } else if (document.selection && document.selection.createRange) {
	        range = document.selection.createRange();
	        range.text = replacementText;
	    }
	},
	getSelectedNode : function ()
	{
		var node, selection = this.getSel();
		if (window.getSelection)
		{
			node = selection.anchorNode;
	        }
		if (!node && document.selection)
		{
			 var range = this.getRng();
			node = range.commonAncestorContainer ? range.commonAncestorContainer : range.parentElement ? range.parentElement() : range.item(0);
		}
		if (node)
		{
			return (node.nodeName == "#text" ? node.parentNode : node);
		}
	},
	selRng : function(rng,s) {
		if(window.getSelection) {
			s.removeAllRanges();
			s.addRange(rng);
		} else {
			rng.select();
		}
	},
	
	selElm : function() {
		var r = this.getRng();
		if(!r) { return; }
		if(r.startContainer) {
			var contain = r.startContainer;
			if(r.cloneContents().childNodes.length == 1) {
				for(var i=0;i<contain.childNodes.length;i++) {
					var rng = contain.childNodes[i].ownerDocument.createRange();
					rng.selectNode(contain.childNodes[i]);					
					if(r.compareBoundaryPoints(Range.START_TO_START,rng) != 1 && 
						r.compareBoundaryPoints(Range.END_TO_END,rng) != -1) {
						return $Z(contain.childNodes[i]);
					}
				}
			}
			return $Z(contain);
		} else {
			return $Z((this.getSel().type == "Control") ? r.item(0) : r.parentElement());
		}
	},
	
	saveRng : function() {
		this.savedRange = this.getRng();
		this.savedSel = this.getSel();
	},
	
	restoreRng : function() {
		if(this.savedRange) {
			this.selRng(this.savedRange,this.savedSel);
		}
	},
	
	keyDown : function(e,t) {

		if(e.ctrlKey) {
			this.ne.fireEvent('key',this,e);
		}
		if(e.keyCode==9){
			this.ne.nicCommand("insertHTML",'&nbsp;&nbsp;&nbsp;&nbsp;');
			if(e.preventDefault) e.preventDefault();
		}
	},
	
	selected : function(e,t) {
		//klj
		if(!t) return;
		//eof
		if(!t && !(t = this.selElm)) { t = this.selElm(); }
		if(!e.ctrlKey) {
			var selInstance = this.ne.selectedInstance;
			if(selInstance != this) {
				if(selInstance) {
					this.ne.fireEvent('blur',selInstance,t);
				}
				this.ne.selectedInstance = this;	
				this.ne.fireEvent('focus',selInstance,t);
			}
			this.ne.fireEvent('selected',selInstance,t);
			this.isFocused = true;
			this.elm.addClass(zmdoc._editor_cls_prefix+'selected');
		}
		return false;
	},
	
	blur : function() {
		this.isFocused = false;
		this.elm.removeClass(zmdoc._editor_cls_prefix+'selected');
	},
	
	saveContent : function() {
		this.e.value = this.getContent();
	},
	
	getElm : function() {
		return this.elm;
	},
	
	getContent : function() {
		this.content = this.getElm().innerHTML;
		this.ne.fireEvent('get',this);
		return this.content;
	},

	setContent: function(e) {
		this.html(e);
	},
	
	html : function(e) {
		this.content = e;
		this.ne.fireEvent('set',this);
		this.elm.innerHTML = this.content;	
	},
	
	nicCommand : function(cmd,args) {
		
		document.execCommand(cmd,false,args);
	}		
});

//overide nicEditorInstance

var nicEditorIFrameInstance = nicEditorInstance.extend({
	savedStyles : [],//for iframe body style
	
	init : function() {	
		var c = this.elm.innerHTML.replace(/^\s+|\s+$/g, '');
		this.elm.innerHTML = '';
		(!c) ? c = "<br />" : c;
		this.initialContent = c;
		
		this.elmFrame = new $ZElement('iframe').attr({'src' : 'javascript:;', 'frameBorder' : 0, 'allowTransparency' : 'true', 'scrolling' : 'no'}).css({height: '100px', width: '100%'}).addClass(zmdoc._editor_cls_prefix+'frame').wrapper(this.elm);

		if(this.copyElm) { this.elmFrame.css({width : (this.elm.offsetWidth-4)+'px'}); }
		
		var styleList = ['font-size','font-family','font-weight','color'];
		for(itm in styleList) {
			this.savedStyles[$Z.camelize(itm)] = this.elm.css(itm); //y only this？
		}
     	
		setTimeout(this.initFrame.closure(this),50);
	},
	
	disable : function() {
		this.elm.innerHTML = this.getContent();
	},
	
	initFrame : function() {
		var fd = $Z(this.elmFrame.contentWindow.document);
		fd.designMode = "on";		
		fd.open();
		fd.write('<html><head><link rel="stylesheet" type="text/css" href="'+this.ne.options.ZMDOCSTYLE+' /></head><body id="nicEditContent" style="margin: 0 !important; background-color: transparent !important;">'+this.initialContent+'</body></html>');
		fd.close();
		this.frameDoc = fd;

		this.frameWin = $Z(this.elmFrame.contentWindow);
		this.frameContent = $Z(this.frameWin.document.body).css(this.savedStyles);
		this.instanceDoc = this.frameWin.document.defaultView;
		
		this.heightUpdate();
		this.frameDoc.on('mousedown', this.selected.closureListener(this)).on('keyup',this.heightUpdate.closureListener(this)).on('keydown',this.keyDown.closureListener(this)).on('keyup',this.selected.closure(this));
		this.ne.fireEvent('add',this);
	},
	
	getElm : function() {
		return this.frameContent;
	},
	
	html : function(c) {
		this.content = c;
		this.ne.fireEvent('set',this);
		this.frameContent.innerHTML = this.content;	
		this.heightUpdate();
	},
	
	getSel : function() {
		return (this.frameWin) ? this.frameWin.getSelection() : this.frameDoc.selection;
	},
	
	heightUpdate : function() {	
		this.elmFrame.style.height = Math.max(this.frameContent.offsetHeight,this.initialHeight)+'px';
	},
    
	nicCommand : function(cmd,args) {
		this.frameDoc.execCommand(cmd,false,args);
		setTimeout(this.heightUpdate.closure(this),100);//remove the innerFrame scrollBar
	}
});

//=========================

//工具栏
var nicEditorTools = $ZClass.extend({
	construct : function(e,options,nicEditor) {
		this.elm = e;
		this.options = options;
		this.ne = nicEditor;
		this.panelButtons = new Array();
		this.buttonList = $ZExtend([],this.ne.options.buttonList);
		
		this.panelContain = new $ZElement('DIV').attr({"style":"overflow:hidden;background: #f1f1f1;background: -moz-linear-gradient(top,  #f1f1f1 0%, #e2e2e2 100%);background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f1f1f1), color-stop(100%,#e2e2e2));background: -webkit-linear-gradient(top,  #f1f1f1 0%,#e2e2e2 100%);background: -o-linear-gradient(top,  #f1f1f1 0%,#e2e2e2 100%);background: -ms-linear-gradient(top,  #f1f1f1 0%,#e2e2e2 100%);background: linear-gradient(to bottom,  #f1f1f1 0%,#e2e2e2 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f1f1f1', endColorstr='#e2e2e2',GradientType=0 );border-bottom: 1px solid #bbb;"}).addClass(zmdoc._editor_cls_prefix+'panelContain');
		this.panelElm = new $ZElement('DIV').css({zoom : 1, overflow : 'hidden'}).addClass(zmdoc._editor_cls_prefix+'panel').wrapper(this.panelContain);
		

		this.panelContain.wrapper(e);
		this.sctop = this.panelContain.pos()[1];

		var opt = this.ne.options;
		var buttons = opt.buttons;
		for(button in buttons) {
				this.addButton(button,opt,true);
		}
		this.reorder();
		e.noSelect();
	},
	
	addButton : function(buttonName,options,noOrder) {
		var button = options.buttons[buttonName];
		var type = (button['type']) ? eval('(typeof('+button['type']+') == "undefined") ? null : '+button['type']+';') : nicEditorButton;
		var hasButton = $Z.inArray(this.buttonList,buttonName);
		if(type && (hasButton || this.ne.options.fullPanel)) {
			this.panelButtons.push(new type(this.panelElm,buttonName,options,this.ne));
		}
	},
	
	findButton : function(itm) {
		for(var i=0;i<this.panelButtons.length;i++) {
			if(this.panelButtons[i].name == itm)
				return this.panelButtons[i];
		}	
	},
	
	reorder : function() {
		var bl = this.buttonList;
		for(var i=0;i<bl.length;i++) {
			var button = this.findButton(bl[i]);
			if(button) {
				//move button
				this.panelElm.appendChild(button.contain);
			}
		}	
	},
	
	remove : function() {
		this.elm.remove();
	}
});
var nicEditorButton = $ZClass.extend({
	
	construct : function(e,buttonName,options,nicEditor) {
		this.options = options.buttons[buttonName];
		this.name = buttonName;
		this.ne = nicEditor;
		this.elm = e;
		this.contain = new $ZElement('DIV').css({width : '25px', height : '25px', 'float':'left', margin:'1px'}).addClass(zmdoc._editor_cls_prefix+'buttonContain').wrapper(e);
		this.button = new $ZElement('DIV').css({width : '25px', height : '25px', overflow : 'hidden', zoom : 1, cursor : 'pointer'}).addClass(zmdoc._editor_cls_prefix+'button').css(this.ne.getIcon(buttonName,options)).wrapper(this.contain);
		this.button.on('mouseover', this.hoverOn.closure(this)).on('mouseout',this.hoverOff.closure(this)).on('mousedown',this.mouseClick.closure(this)).noSelect();
		
		if(!window.opera) {
			this.button.onmousedown = this.button.onclick = $Z.cancelEvent;
		}
		
		nicEditor.on('selected', this.enable.closure(this)).on('blur', this.disable.closure(this)).on('key',this.key.closure(this));
		
		this.disable();
		this.init();
	},
	
	init : function() {  },
	
	hide : function() {
		this.contain.css({display : 'none'});
	},
	
	updateState : function() {
		if(this.isDisabled) { this.setBg(); }
		else if(this.isHover) { this.setBg('hover'); }
		else if(this.isActive) { this.setBg('active'); }
		else { this.setBg('normal'); }
	},
	
	setBg : function(state) {
		switch(state) {
			case 'hover':
				var stateStyle = {border : '1px solid #666', backgroundColor : '#ddd'};
				break;
			case 'active':
				var stateStyle = {border : '1px solid #666', backgroundColor : '#ccc'};
				break;
			default:
				var stateStyle = {border : '1px solid transparent', backgroundColor : 'transparent'};	
		}
		this.contain.css(stateStyle).addClass(zmdoc._editor_cls_prefix+'button-'+state);
	},
	
	checkNodes : function(e) {
		var elm = e;	
		do {
			if(this.options.tags && $Z.inArray(this.options.tags,elm.nodeName)) {
				this.activate();
				return true;
			}
		} while(elm = elm.parentNode && elm.className != "zmdoc");
		elm = $Z(e);
		while(elm.nodeType == 3) {
			elm = $Z(elm.parentNode);
		}
		if(this.options.css) {
			for(itm in this.options.css) {
				if(elm.css(itm,this.ne.selectedInstance.instanceDoc) == this.options.css[itm]) {
					this.activate();
					return true;
				}
			}
		}
		this.deactivate();
		return false;
	},
	
	activate : function() {
		if(!this.isDisabled) {
			this.isActive = true;
			this.updateState();	
			this.ne.fireEvent('buttonActivate',this);
		}
	},
	
	deactivate : function() {
		this.isActive = false;
		this.updateState();	
		if(!this.isDisabled) {
			this.ne.fireEvent('buttonDeactivate',this);
		}
	},
	
	enable : function(ins,t) {
		this.isDisabled = false;
		this.contain.css({'opacity' : 1}).addClass(zmdoc._editor_cls_prefix+'buttonEnabled');
		this.updateState();
		this.checkNodes(t);
	},
	
	disable : function(ins,t) {		
		this.isDisabled = true;
		this.contain.css({'opacity' : 0.6}).removeClass(zmdoc._editor_cls_prefix+'buttonEnabled');
		this.updateState();	
	},
	
	toggleActive : function() {
		(this.isActive) ? this.deactivate() : this.activate();	
	},
	
	hoverOn : function() {
		if(!this.isDisabled) {
			this.isHover = true;
			this.updateState();
			this.ne.fireEvent("buttonOver",this);
		}
	}, 
	
	hoverOff : function() {
		this.isHover = false;
		this.updateState();
		this.ne.fireEvent("buttonOut",this);
	},
	
	mouseClick : function() {
		if(this.isDisabled) return;
		if(this.options.command) {
			this.ne.nicCommand(this.options.command,this.options.commandArgs);
			if(!this.options.noActive) {
				this.toggleActive();
			}
		}
		this.ne.fireEvent("buttonClick",this);
	},
	
	key : function(nicInstance,e) {
		if(this.options.key && e.ctrlKey && String.fromCharCode(e.keyCode || e.charCode).toLowerCase() == this.options.key) {
			this.mouseClick();
			if(e.preventDefault) e.preventDefault();
		}
	}
	
});

//普通面板插件？
var nicPlugin = $ZClass.extend({
	
	construct : function(nicEditor,options) {
		this.options = options;
		this.ne = nicEditor;
		this.ne.on('panel',this.loadPanel.closure(this));
		
		this.init();
	},

	loadPanel : function(np) {
		var buttons = this.options.buttons;
		for(var button in buttons) {
			np.addButton(button,this.options);
		}
		np.reorder();
	},

	init : function() {  }
});



 
 /* START CONFIG */
var nicPaneOptions = { };
/* END CONFIG */

var nicEditorPane = $ZClass.extend({
	construct : function(elm,nicEditor,options,openButton) {
		this.ne = nicEditor;
		this.elm = elm;

	
		//this.pos = elm.pos();

		this.pos = [elm.offsetLeft,Math.ceil(elm.offsetTop/30)*30];


		this.contain = new $ZElement('div').css({zIndex : '99999', overflow : 'hidden', position : 'absolute', left : this.pos[0]+'px', top : this.pos[1]+'px'});
		this.pane = new $ZElement('div').css({fontSize : '12px', border : '1px solid #ccc', 'overflow': 'hidden', padding : '4px', textAlign: 'left', backgroundColor : '#ffffc9'}).addClass(zmdoc._editor_cls_prefix+'pane').css(options).wrapper(this.contain);
		
		if(openButton && !openButton.options.noClose) {
			this.close = new $ZElement('div').css({'float' : 'right', height: '25px', width : '25px', cursor : 'pointer'}).css(this.ne.getIcon('close',nicPaneOptions)).on('mousedown',openButton.removePane.closure(this)).wrapper(this.pane);
		}
	
		this.contain.noSelect().wrapper(this.ne.nicPanel.elm);
		
		this.position();
		this.init();	
	},
	
	init : function() { },
	
	position : function() {
		if(this.ne.nicPanel) {
			var panelElm = this.ne.nicPanel.elm;	
		
			var newLeft = parseInt(panelElm.css('width'))-(parseInt(this.pane.css('width'))+12);

			if(newLeft < this.pos[0]) {//align right
				this.contain.css({left : Math.max(-1,newLeft)+'px'});//no hidden
			}
		}
	},
	
	toggle : function() {
		this.isVisible = !this.isVisible;
		this.contain.css({display : ((this.isVisible) ? 'block' : 'none')});
	},
	
	remove : function() {
		if(this.contain) {
			this.contain.remove();
			this.contain = null;
		}
	},
	
	append : function(c) {

		c.wrapper(this.pane);
	},
	
	html : function(c) {
		this.pane.html(c);
	}
	
});


 
var nicEditorAdvancedButton = nicEditorButton.extend({
	
	init : function() {
		this.ne.on('selected',this.removePane.closure(this)).on('blur',this.removePane.closure(this));	
	},
	
	mouseClick : function() {
		if(!this.isDisabled) {
			if(this.pane && this.pane.pane) {
				this.removePane();
			} else {
				this.pane = new nicEditorPane(this.contain,this.ne,{width : (this.width || '270px'), backgroundColor : '#fff'},this);
				this.addPane();
				this.ne.selectedInstance.saveRng();
			}
		}
	},
	
	
	
	submit : function() { },
	
	findElm : function(tag,attr,val) {
		var list = this.ne.selectedInstance.getElm().getElementsByTagName(tag);
		for(var i=0;i<list.length;i++) {
			if(list[i].getAttribute(attr) == val) {
				return $Z(list[i]);
			}
		}
	},
	
	removePane : function() {
		if(this.pane) {
			this.pane.remove();
			this.pane = null;
			this.ne.selectedInstance.restoreRng();
		}	
	}	
});


var nicButtonTips = $ZClass.extend({
	construct : function(nicEditor) {
		this.ne = nicEditor;
		nicEditor.on('buttonOver',this.show.closure(this)).on('buttonOut',this.hide.closure(this));

	},
	
	show : function(button) {
		this.timer = setTimeout(this.create.closure(this,button),400);
	},
	
	create : function(button) {
		this.timer = null;
		if(!this.pane) {
			this.pane = new nicEditorPane(button.button,this.ne,{fontSize : '12px', marginTop : '5px'});
			this.pane.html(button.options.name);
		}		
	},
	
	hide : function(button) {
		if(this.timer) {
			clearTimeout(this.timer);
		}
		if(this.pane) {
			this.pane = this.pane.remove();
		}
	}
});
//nicEditors.registerPlugin(nicButtonTips);
nicPlugins.push({p : nicButtonTips});
	



/* START CONFIG */
var nicLinkOptions = {
	buttons : {
		'link' : {name : nicLang.link, type : 'nicLinkButton', tags : ['A']},
		'unlink' : {name : nicLang.unlink,  command : 'unlink', noActive : true}
	}
};
/* END CONFIG */

var nicLinkButton = nicEditorAdvancedButton.extend({
	width:'340px',
	addPane : function() {
		var url = 'http://',checked = '';
		this.ln = this.ne.selectedInstance.selElm().parentTag('A');
		if(this.ln){
			url = this.ln.attr('href'),checked = (this.ln.attr('target')=='_blank')?' checked="checked"':'';
		}

		var frm = new $ZElement('form').on('submit',this.submit.closureListener(this));
		var	html = '<input autocomplete="off" name="href" type="text" style="height:26px;padding:2px;line-height:1;display:block; margin:5px 0;width:100%;box-sizing: border-box;" value="'+url+'" />';
			html += '<button type="submit" style="cursor:pointer;margin-right:1em;">'+nicLang.submit+'</button>';
			html += '<label><input name="target"'+checked+'type="checkbox" style="width:inherit;height:inherit;line-height:1" value="1" name="target" />'+nicLang.links.newWindow+'</label>';
			
		frm.html(html);
		this.pane.append(frm);
		frm.onsubmit = $Z.cancelEvent;
	},
	
	submit : function(e,frm) {
		try{
			var url = frm.elements['href'].value;
			if(url == "http://" || url == "") {
				alert(nicLang.links.error);
				return false;
			}
			this.removePane();
			
			if(!this.ln) {
				var tmp = 'javascript:nicTemp();';
				this.ne.nicCommand("createlink",tmp);
				this.ln = this.findElm('A','href',tmp);
			}

			if(this.ln) {
				this.ln.attr({
					href : frm.elements['href'].value,
					title : frm.elements['href'].value,
					target : (frm.elements['target'].checked)?'_blank':'_self'
				});
			}
		}catch(e){
			console.log(e);
		}
		return false;
		
	}
});

//nicEditors.registerPlugin(nicPlugin,nicLinkOptions);
nicPlugins.push({p : nicPlugin,o:nicLinkOptions});


/* START CONFIG */
var nicColorOptions = {
	buttons : {
		'forecolor' : {name : nicLang.forecolor, type : 'nicEditorColorButton', noClose : true},
		'bgcolor' : {name : nicLang.bgcolor, type : 'nicEditorBgColorButton', noClose : true}
	}
};
/* END CONFIG */

var nicEditorColorButton = nicEditorAdvancedButton.extend({
	width:'198px',
	addPane : function() {
			var colorList = {0 : '00',1 : '33',2 : '66',3 :'99',4 : 'CC',5 : 'FF'};
			
			var colorItems = new $ZElement('DIV').css({className:'clearfix',padding: '2px',backgroundColor:'#EFEFEF'});
			var colors = [
            '000000','333333','808080','999999','C0C0C0','FFFFFF',
            '008000','008080','00FF00','339966','808000','99CC00',
			'800000','993300','FF0000','FF6600','FF9900','FFCC00',
			'000080','333399','0000FF','3366FF','FFFF00','FFFF99',
			'33CCCC','00CCFF','00FFFF','99CCFF','CCFFFF','333300',
			'800080','993366','FF00FF','FF99CC','FFCC99','666699'
       		];

       		colors = ("FFF FCC FC9 FF9 FFC 9F9 9FF CFF CCF FCF " +
                    "CCC F66 F96 FF6 FF3 6F9 3FF 6FF 99F F9F " +
                    "BBB F00 F90 FC6 FF0 3F3 6CC 3CF 66C C6C " +
                    "999 C00 F60 FC3 FC0 3C0 0CC 36F 63F C3C " +
                    "666 900 C60 C93 990 090 399 33F 60C 939 " +
                    "333 600 930 963 660 060 366 009 339 636 " +
                    "000 300 630 633 330 030 033 006 309 303").split(" ");

 
			
			for(i=0; i<colors.length; i++) {
						var colorCode = '#'+colors[i];
						var colorSquare = new $ZElement('DIV').css({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left','margin':'2px'}).wrapper(colorItems);
						var colorBorder = new $ZElement('DIV').css({border: '2px solid '+colorCode}).wrapper(colorSquare);
						var colorInner = new $ZElement('DIV').css({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).on('click',this.colorSelect.closure(this,colorCode)).on('mouseover',this.on.closure(this,colorBorder)).on('mouseout',this.off.closure(this,colorBorder,colorCode)).wrapper(colorBorder);
						
						if(!window.opera) {
							colorSquare.onmousedown = colorInner.onmousedown = $Z.cancelEvent;
						}
			}
			this.pane.append(colorItems.noSelect());	
	},
	
	colorSelect : function(c) {
		this.ne.nicCommand('foreColor',c);
		this.removePane();
	},
	
	on : function(colorBorder) {
		colorBorder.css({border : '2px solid #000'});
	},
	
	off : function(colorBorder,colorCode) {
		colorBorder.css({border : '2px solid '+colorCode});		
	}
});

var nicEditorBgColorButton = nicEditorColorButton.extend({
	colorSelect : function(c) {
		this.ne.nicCommand('hiliteColor',c);
		this.removePane();
	}	
});

//nicEditors.registerPlugin(nicPlugin,nicColorOptions);
nicPlugins.push({p : nicPlugin,o:nicColorOptions});


/* START CONFIG */
var nicImageOptions = {
	buttons : {
		'image' : {name : nicLang.image, type : 'nicImageButton', tags : ['IMG']}
	}
	
};
/* END CONFIG */

var nicImageButton = nicEditorButton.extend({
	construct : function(e,buttonName,options,nicEditor) {
		this.options = options.buttons[buttonName];
		this.elm = e;
		this.ne = nicEditor;
		this.name = buttonName;
		this.selOptions = new Array();
		
		this.contain = new $ZElement('DIV').css({width : '25px', height : '25px',overflow:'hidden', 'float':'left',margin:'1px'}).addClass(zmdoc._editor_cls_prefix+'buttonContain').wrapper(e);
	

		
		this.button = new $ZElement('DIV').css({width : '25px',position:'relative',height : '25px', overflow : 'hidden', zoom : 1, cursor : 'pointer'}).addClass(zmdoc._editor_cls_prefix+'button').css(this.ne.getIcon(buttonName,options)).wrapper(this.contain);
		this.input = new $ZElement('INPUT').attr({'type' : 'file','multiple':'multiple',accept:'image/jpeg,image/png'}).css({position:'absolute',border:'none',width:'1000px',height:'1000px',margin:'-10px -10px 0 0',padding:0, right:0,opacity:0, cursor : 'pointer',fontSize:'1000px'}).wrapper(this.button);
		
		this.button.on('mouseover', this.hoverOn.closure(this)).on('mouseout',this.hoverOff.closure(this)).on('mousedown',this.mouseClick.closure(this)).noSelect();

		this.input.on('change', this.uploaded.closure(this));
		
		if(!window.opera) {
			//this.button.onmousedown = this.button.onclick = $Z.cancelEvent;
		}
		
		nicEditor.on('selected', this.enable.closure(this)).on('blur', this.disable.closure(this)).on('key',this.key.closure(this));
		
		this.disable();
		this.init();
	},
	enable : function(ins,t) {
		this.isDisabled = false;
		this.input.css({'display':'block'});
		this.contain.css({'opacity' : 1}).addClass(zmdoc._editor_cls_prefix+'buttonEnabled');
		this.updateState();
		this.checkNodes(t);
	},
	
	disable : function(ins,t) {		
		this.isDisabled = true;
		this.input.css({'display':'none'});
		this.contain.css({'opacity' : 0.6}).removeClass(zmdoc._editor_cls_prefix+'buttonEnabled');
		this.updateState();	
	},
	uploaded:function(){

		var me = this;

		var passed = true;
		for(var index=0; index<this.input.files.length; index++){
			var File = this.input.files[index];
			if(File.type!="image/jpeg"&&File.type!="image/png"){
				passed = false;
			}
			if(File.size/(1024*1024)>1){
				passed = false;
			}
		}

		if(!passed){
			alert(nicLang.uploadImageTypeLimit+'\n'+nicLang.uploadImageSizeLimit);
			return;
		}

		if(this.input.files.length==0){
			return;
		}


		


		
		var editor = this.ne;
		
		//if(!editor.selectedInstance.selElm().hasClass('selected')){
		//	alert('抱歉，你需要点击按钮中间部份!\n点击编辑区！');
		//	return;
		//};

		editor.mask(nicLang.uploading);

		var xhrs = [], xhrimages = [];

		for(var index=0; index<this.input.files.length; index++){
			var File = this.input.files[index];

			xhrs[index] = new XMLHttpRequest();
			xhrs[index].index = index;
			xhrs[index].open('post', this.ne.options.uploadUrl, true);
			xhrs[index].setRequestHeader("Content-Type", "application/octet-stream");
			xhrs[index].setRequestHeader("X-FILENAME", encodeURI(File.name)||'file');
			xhrs[index].setRequestHeader("X-File-Size", File.fileSize);
			xhrs[index].setRequestHeader("X-File-Type", File.type);
			
			xhrs[index].onreadystatechange = function(){
				if (this.readyState == 4 && this.status == 200){
					var r = {};
					try {
						r = eval("(" + this.responseText + ")");
					} catch(err){}
					if(r.success){
						xhrimages[this.index]=r.addon.url;
						editor.updateMaskText(nicLang.uploading+xhrimages.length+'/'+xhrs.length);
						if(xhrs.length==xhrimages.length){
							//reorder images
							for(img=0; img<xhrimages.length;img++){
							
								//
								editor.nicCommand("insertImage", xhrimages[img]);
							}
						}
					}else{
						alert(r.detail);
					}
					editor.unmask();
				}
				me.input.value = '';
			};
			if ('getAsBinary' in File){
				xhrs[index].sendAsBinary(File.getAsBinary());
			}else{
				xhrs[index].send(File);
			}

		}//end for
		//editor.nicCommand("insertHTML",r.addon.content);
		
	}
});

nicPlugins.push({p : nicPlugin,o:nicImageOptions});


/*files===*/
/* START CONFIG */
var nicUploadOptions = {
	buttons : {
		'upload' : {name : nicLang.uploadFile, type : 'nicUploadButton'}
	}
	
};
/* END CONFIG */

var nicUploadButton = nicImageButton.extend({
	construct : function(e,buttonName,options,nicEditor) {
		this.options = options.buttons[buttonName];
		this.elm = e;
		this.ne = nicEditor;
		this.name = buttonName;
		this.selOptions = new Array();
		
		this.contain = new $ZElement('DIV').css({width : '25px', height : '25px',overflow:'hidden', 'float':'left',margin:'1px'}).addClass(zmdoc._editor_cls_prefix+'buttonContain').wrapper(e);
	
		this.button = new $ZElement('DIV').css({width : '25px',position:'relative',height : '25px', overflow : 'hidden', zoom : 1, cursor : 'pointer'}).addClass(zmdoc._editor_cls_prefix+'button').css(this.ne.getIcon(buttonName,options)).wrapper(this.contain);
		this.input = new $ZElement('INPUT').attr({'type' : 'file','accept':this.ne.options.accept||'*'}).css({position:'absolute',border:'none',width:'1000px',height:'1000px',margin:'-10px -10px 0 0',padding:0, right:0,opacity:0, cursor : 'pointer',fontSize:'1000px'}).wrapper(this.button);
		
		this.button.on('mouseover', this.hoverOn.closure(this)).on('mouseout',this.hoverOff.closure(this)).on('mousedown',this.mouseClick.closure(this)).noSelect();

		this.input.on('change', this.uploaded.closure(this));
		
		if(!window.opera) {
			//this.button.onmousedown = this.button.onclick = $Z.cancelEvent;
		}
		
		nicEditor.on('selected', this.enable.closure(this)).on('blur', this.disable.closure(this)).on('key',this.key.closure(this));
		
		this.disable();
		this.init();
	},

	uploaded:function(){
		var ne = this.ne;
		var me = this;
		
		var File = this.input.files[0];

		if(ne.options.accept && (!File.type || ne.options.accept.indexOf(File.type) < 0)){
			var arr = ne.options.accept.split(',');
			var arrFileType = [];
			try {
				for(var i=0,len=arr.length;i<len;i++) {
					arrFileType.push(arr[i].split('/')[1]);
				}
			} catch(e) {};
			alert(nicLang.uploadFileTypeLimit.replace('XXX',arrFileType.join(',')));
			return;
		}
		if(this.input.files.length==0){
			return;
		}
		ne.mask(nicLang.uploading);

		if(typeof uploadChunkFile == 'function') {
			var fileChunk = new uploadChunkFile({
				el:this.input,
				uploadUrl: this.ne.options.uploadFileUrl || '/app/uploadFile',
				simultaneousUploads:6,
				progress:function(uploaded,total) {
					ne.updateMaskText(((uploaded*1.0 / total) * 100).toFixed() + "%");
				},
				uploading:function(res) {
					if(!res.success) {
						alert('上传错误!');
					}
				},
				finish:function(res) {
					if(res.success) {
						ne.nicCommand("insertHTML",res.addon.content);
					} else {
						alert('上传错误!');
					}
					ne.unmask();
					me.input.value = '';
				}
			});
			fileChunk.start();
		} else {
			var xhr = new XMLHttpRequest();
			xhr.open('post', this.ne.options.uploadFileUrl, true);
			xhr.setRequestHeader("Content-Type", "application/octet-stream");
			xhr.setRequestHeader("X-FILENAME", encodeURI(File.name)||'file');
			xhr.setRequestHeader("X-File-Size", File.fileSize);
			xhr.setRequestHeader("X-File-Type", File.type);


			xhr.upload.addEventListener("progress", function (event) {
				if (event.lengthComputable) {
					ne.updateMaskText(((event.loaded / event.total) * 100).toFixed() + "%");
				}
			}, false);
			
		
			xhr.onreadystatechange = function(){
				if (xhr.readyState == 4 && xhr.status == 200){
					var r = {};
					try {
						r = eval("(" + xhr.responseText + ")");
					} catch(err){}
					if(r.success){

						ne.nicCommand("insertHTML",r.addon.content);
					}else{
						alert(r.detail);
					}
					ne.unmask();
				}
				me.input.value = '';
			};	 
			if ('getAsBinary' in File){
				xhr.sendAsBinary(File.getAsBinary());
			}else{
				xhr.send(File);
			}
		}
	}
	
});

nicPlugins.push({p : nicPlugin,o:nicUploadOptions});



/* START CONFIG */
var nicCodeOptions = {
	buttons : {
		'xhtml' : {name : 'Edit HTML', type : 'nicCodeButton',noClose : true}
	}
	
};
/* END CONFIG */

var nicCodeButton = nicEditorAdvancedButton.extend({
	mouseClick : function() {
		if(!this.isDisabled) {
			if(this.pane && this.pane.pane) {
				this.removePane();
			} else {
				var elm = this.ne.selectedInstance.getElm();
				var w = (parseInt(elm.css('width'))-2)+'px';
			
				this.pane = new nicEditorPane(this.contain,this.ne,{width :w, backgroundColor : '#fff'},this);
				this.addPane();
				this.ne.selectedInstance.saveRng();
			}
		}
	},
		
	addPane : function() {
		var elm = this.ne.selectedInstance.getElm();
		var v = this.ne.selectedInstance.getContent();
			v = v.replace(/&lt;/img,'&amp;lt;').replace(/&gt;/img,'&amp;gt;');
		this.txt = new $ZElement('textarea').css({
			width:elm.css('width'),
			height:elm.css('height'),
			backgroundColor:'#ffffc9',
			resize:'none',
			padding:'3px',
			'font-family':'courier',
			'font-size':'11px',	
			'border':'1px dotted #AAA',
			'line-height':2,
			'color':'#333',
			'-webkit-box-sizing': 'border-box',
		     '-moz-box-sizing': 'border-box',
		          'box-sizing': 'border-box'
		}).html(v);

		this.pane.append(this.txt);
	},
	removePane : function() {
		if(this.pane) {
			this.ne.selectedInstance.html(this.txt.value);
			this.pane.remove();
			this.pane = null;
			this.ne.selectedInstance.restoreRng();
		}	
	}
});

//nicEditors.registerPlugin(nicPlugin,nicCodeOptions);
nicPlugins.push({p : nicPlugin,o:nicCodeOptions});

if(typeof Ext != 'undefined') {
	Ext.ns('Ext.ux.form');
	Ext.ux.form.Editor = Ext.extend(Ext.form.TextArea,  {
	    
	    editor:null,
	    uploadUrl:'/admin/app/addImage',
	    uploadFileUrl:'/admin/app/addFile',
	    editorCss: (zmdoc && zmdoc.editorCss) ? zmdoc.editorCss : 'http://www.dasdoc.com/resource/zmdoc.css',
	    emptyText:'<br>',
	    editorWidth:800,
	    height:600,
	    buttonList : ['bold','italic','underline','h1','h2','p','left','center','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor','xhtml'],
	    
	    afterRender : function(ct, position){
	        Ext.ux.form.Editor.superclass.afterRender.call(this, ct, position);
	        this.el.id = this.el.id || Ext.id();
	        //init value
	        
	        if(!this.uploadFileUrl) {
	            this.buttonList.remove('upload');
	        }
	        
	        this.editor = new nicEditor(this.el.id,{'uploadUrl':this.uploadUrl
	            ,'uploadFileUrl':this.uploadFileUrl
	            ,'ZMDOCSTYLE':this.editorCss
	            ,'accept':this.accept
	            ,width:this.editorWidth
	            ,buttonList:this.buttonList
	        });
	    },
	    
	    setValue: function(v) {
	        Ext.ux.form.Editor.superclass.setValue.call(this, v);
	        if(this.editor) {
	            this.editor.selectedInstance.html(v);
	        }
	    },
	    
	    setActiveError: function(msg, suppressEvent) {
	        Ext.ux.form.Editor.superclass.setActiveError.call(this,msg, suppressEvent);
	        if (suppressEvent !== true && this.errorIcon && this.editor) {
	            this.errorIcon.alignTo(this.editor.nicPanel.elm,'tr');
	        }
	    }
	});

	Ext.reg('editor', Ext.ux.form.Editor);
}